package org.jeecg.modules.basic.material.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.entity.BasicMaterialVO;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfo;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfoVO;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.material.service.IWmsBasicMaterialStockInfoService;
import org.jeecg.modules.basic.materialtype.service.IBasicMaterialTypeService;
import org.jeecg.modules.basic.unit.service.IBasicUnitService;
import org.jeecg.modules.business.job.service.SyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 物料信息管理
 * @Author: jeecg-boot
 * @Date: 2023-08-02
 * @Version: V1.0
 */
@Api(tags = "物料信息管理")
@RestController
@RequestMapping("/material")
@Slf4j
public class BasicMaterialController extends JeecgController<BasicMaterial, IBasicMaterialService> {
    @Autowired
    private IBasicMaterialService basicMaterialService;

    @Autowired
    private IBasicMaterialTypeService basicMaterialTypeService;
    @Autowired
    private SyncService syncService;
    @Autowired
    private IBasicUnitService basicUnitService;
    @Autowired
    private IWmsBasicMaterialStockInfoService wmsBasicMaterialStockInfoService;

    @Value("${transtella.bus.factory}")
    private String factory;

    /**
     * 分页列表查询
     *
     * @param basicMaterial
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "物料信息管理-分页列表查询", notes = "物料信息管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Page<BasicMaterial>> queryPageList(BasicMaterial basicMaterial,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<Page<BasicMaterial>> result = new Result<Page<BasicMaterial>>();
        Page<BasicMaterial> pageList = new Page<BasicMaterial>(pageNo, pageSize);
        pageList = basicMaterialService.listMaterialByPage(pageList, basicMaterial);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param basicMaterial
     * @return
     */
    @AutoLog(value = "物料信息管理-添加")
    @ApiOperation(value = "物料信息管理-添加", notes = "物料信息管理-添加")
    @RequiresPermissions("basic:material:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BasicMaterialVO basicMaterial) {
        BasicMaterial material = BeanUtil.toBean(basicMaterial,BasicMaterial.class);
        material.setUsed(0);
        basicMaterialService.save(material);
        WmsBasicMaterialStockInfoVO vo = new WmsBasicMaterialStockInfoVO();
        vo.setMaterialId(material.getId());
        List<WmsBasicMaterialStockInfo> saveList = basicMaterial.getList();
        if (ObjectUtil.isNotEmpty(saveList)) {
            saveList.forEach(info -> {
                info.setWmsBasicMaterialId(material.getId());
            });
        }
        vo.setList(saveList);
        wmsBasicMaterialStockInfoService.saveDataByCheck(vo);
        try {
            basicMaterialTypeService.updateUsedState(material.getMaterialTypeId());
            ArrayList<String> strings = new ArrayList<>();
            strings.add(material.getAssistantUnitId());
            strings.add(material.getInventoryUnitId());
            basicUnitService.updateUsed(strings);
        } catch (Exception e) {
            log.error("更新物料分类出错", e);
        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param basicMaterial
     * @return
     */
    @AutoLog(value = "物料信息管理-编辑")
    @ApiOperation(value = "物料信息管理-编辑", notes = "物料信息管理-编辑")
    @RequiresPermissions("basic:material:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BasicMaterialVO basicMaterial) {
        List<WmsBasicMaterialStockInfo> list = basicMaterial.getList();
        for (int i = 0; i < list.size(); i++) {
            for (int j = i+1; j < list.size(); j++) {
                if (list.get(i).getWarehouseId().equals(list.get(j).getWarehouseId())
                        && list.get(i).getWarehouseAreaId().equals(list.get(j).getWarehouseAreaId())) {
                    throw new JeecgBootException("物料库存信息存在重复设置!");
                }
            }
        }

        BasicMaterial material = BeanUtil.toBean(basicMaterial,BasicMaterial.class);
        if (StringUtils.isNotBlank(material.getMaxInventory())
                && StringUtils.isNotBlank(material.getSafeInventory())) {
            int maxInventory = Integer.parseInt(material.getMaxInventory());
            int safeInventory = Integer.parseInt(material.getSafeInventory());
            if (safeInventory > maxInventory) {
                throw new JeecgBootException("安全库存不能大于最大库存!");
            }
        }
        if (StringUtils.isNotBlank(material.getMinInventory())
                && StringUtils.isNotBlank(material.getSafeInventory())) {
            int minInventory = Integer.parseInt(material.getMinInventory());
            int safeInventory = Integer.parseInt(material.getSafeInventory());
            if (safeInventory < minInventory) {
                throw new JeecgBootException("安全库存不能小于最小库存!");
            }
        }
        if (StringUtils.isNotBlank(material.getNumber()) && StringUtils.isBlank(material.getAssistantUnitId())) {
            //传入换算数量,但是不传辅助单位报错
            throw new JeecgBootException("请选择辅助单位!");
        }
        if (StringUtils.isNotBlank(material.getSafeInventory())
                && StringUtils.isBlank(material.getMinInventory())
                && StringUtils.isBlank(material.getMaxInventory())
        ) {
            //只有安全库存,没有最大库存和最小库存报错
            throw new JeecgBootException("请选择最大库存或者最小库存");
        }
        WmsBasicMaterialStockInfoVO vo = new WmsBasicMaterialStockInfoVO();
        vo.setMaterialId(basicMaterial.getId());
        vo.setList(basicMaterial.getList());
        wmsBasicMaterialStockInfoService.saveDataByCheck(vo);
        basicMaterialService.updateById(material);
        try {
            basicMaterialTypeService.updateUsedState(material.getMaterialTypeId());
            ArrayList<String> strings = new ArrayList<>();
            strings.add(material.getAssistantUnitId());
            strings.add(material.getInventoryUnitId());
            basicUnitService.updateUsed(strings);
        } catch (Exception e) {
            log.error("更新物料分类出错", e);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料信息管理-通过id删除")
    @ApiOperation(value = "物料信息管理-通过id删除", notes = "物料信息管理-通过id删除")
    @RequiresPermissions("basic:material:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        BasicMaterial byId = basicMaterialService.getById(id);
        basicMaterialService.removeById(id);
        List<WmsBasicMaterialStockInfo> list = wmsBasicMaterialStockInfoService.list(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>().eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, id));
        if (ObjectUtil.isNotEmpty(list)) {
            List<String> ids = list.stream().map(WmsBasicMaterialStockInfo::getId).collect(Collectors.toList());
            wmsBasicMaterialStockInfoService.removeBatchByIds(ids);
        }
        try {
            basicMaterialTypeService.updateUsedState(byId.getMaterialTypeId());
            ArrayList<String> strings = new ArrayList<>();
            strings.add(byId.getAssistantUnitId());
            strings.add(byId.getInventoryUnitId());
            basicUnitService.updateUsed(strings);
        } catch (Exception e) {
            log.error("更新物料分类出错", e);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料信息管理-批量删除")
    @ApiOperation(value = "物料信息管理-批量删除", notes = "物料信息管理-批量删除")
    @RequiresPermissions("basic:material:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<BasicMaterial> materials = basicMaterialService.listByIds(Arrays.asList(ids.split(",")));
        this.basicMaterialService.removeByIds(Arrays.asList(ids.split(",")));
        try {
            for (BasicMaterial material : materials) {
                basicMaterialTypeService.updateUsedState(material.getMaterialTypeId());
                ArrayList<String> strings = new ArrayList<>();
                strings.add(material.getAssistantUnitId());
                strings.add(material.getInventoryUnitId());
                basicUnitService.updateUsed(strings);
            }
        } catch (Exception e) {
            log.error("更新物料分类出错", e);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "物料信息管理-通过id查询")
    @ApiOperation(value = "物料信息管理-通过id查询", notes = "物料信息管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BasicMaterial> queryById(@RequestParam(name = "id", required = true) String id) {
        BasicMaterial basicMaterial = basicMaterialService.getById(id);
        if (basicMaterial == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(basicMaterial);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param basicMaterial
     */
    @RequiresPermissions("basic:material:export")
    @ApiOperation(value = "物料信息管理-导出excel", notes = "物料信息管理-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicMaterial basicMaterial) {
        return super.exportXlsSheet(request, basicMaterial, BasicMaterial.class, "物料信息管理",null,10000);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @return
     */
    @RequiresPermissions("basic:material:import")
    @ApiOperation(value = "物料信息管理-通过excel导入数据", notes = "物料信息管理-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request) {
        return basicMaterialService.importExcel(request);
    }


    /**
     * 同步物料信息
     *
     * @return
     */
    @ApiOperation(value = "物料信息管理-同步物料信息", notes = "物料信息管理-同步物料信息")
    @GetMapping(value = "/sync-material")
    public Result syncMaterial(@RequestParam(value = "beforeDay") Integer beforeDay) {
        syncService.syncMaterial(beforeDay);
        return Result.OK("同步物料信息成功！");
    }

    /**
     * 查询物料集合
     *
     * @return
     */
    @ApiOperation(value = "物料信息管理-查询物料集合", notes = "物料信息管理-查询物料集合")
    @GetMapping(value = "/getMaterialList")
    public Result<List<BasicMaterial>> getMaterialListByMaterialTypes(@RequestParam(value = "materialTypes", required = false) String materialTypes,
                                                                      @RequestParam(value = "materialCode", required = false) String materialCode) {
        List<String> list = Arrays.asList(StrUtil.split(materialTypes, ","));
        LambdaQueryWrapper<BasicMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isNotEmpty(list)) {
            queryWrapper.in(BasicMaterial::getMaterialTypeId, list);
        }
        if (StringUtils.isNotBlank(materialCode)) {
            queryWrapper.like(BasicMaterial::getCode, materialCode);
        }
        queryWrapper.last("limit 100");
        List<BasicMaterial> res = basicMaterialService.list(queryWrapper);
        return Result.OK(res);
    }
}
